package systemapi

import (
	"bytes"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"iot-base/common/netip"
	"iot-base/common/webapi"
	"os"
	"os/exec"
	"path/filepath"
)

//IPCfg ip配置
type IPCfgJson struct {
	Name    string `json:"cardName"`
	IP      string `json:"ip"`
	NetMask string `json:"mask"`
	Gateway string `json:"gw"`
	Mac     string `json:"mac"`
	NetType string `json:"type"`
	DNS     string `json:"dns"`
	//InterfaceName string
}

func SetAddr(ipC IPCfgJson) (interface{}, error) {
	if ipC.Name == "" || ipC.IP == "" || ipC.NetType == "" || ipC.NetMask == "" || ipC.NetType == "" {

		return nil, errors.New("param is empty")
	}
	file, _ := exec.LookPath(os.Args[0])
	path, _ := filepath.Abs(file)
	dir := filepath.Dir(path)
	scriptpath := fmt.Sprintf("sudo %s/update_ip.sh %s %s %s %s %s %s", dir, ipC.IP, ipC.NetMask,
		ipC.Gateway, ipC.DNS, ipC.NetType, ipC.Name)
	fmt.Println("-----", scriptpath)
	pCmd := exec.Command("/bin/sh", "-c", scriptpath)
	var out bytes.Buffer
	pCmd.Stdout = &out
	pCmd.Stderr = os.Stderr
	err := pCmd.Start()
	if err != nil {

		return nil, err
	}
	err = pCmd.Wait()
	if err != nil {

		return nil, err
	}
	//webapi.SendResult(out.String(), err, c)
	return out.String(), err
}

func GetAddr() ([]IPCfgJson, error) {
	result, err := netip.GetIPs()
	nlen := len(result)
	if nlen > 0 {
		jresult := make([]IPCfgJson, nlen)
		for i, ip := range result {
			jresult[i].Name = ip.Name
			jresult[i].IP = ip.IP
			jresult[i].NetMask = ip.NetMask
			jresult[i].Gateway = ip.Gateway
			jresult[i].Mac = ip.Mac

		}
		//webapi.SendResult(jresult, err, c)
		return jresult, err
	} else {
		return nil, err
	}
}

func initIPApi(cfg *gin.RouterGroup) {
	g := cfg.Group("/net")
	{
		g.GET("/", func(c *gin.Context) {
			jresult, err := GetAddr()
			webapi.SendResult(jresult, err, c)

		})
		g.PUT("/", func(c *gin.Context) {
			var ipC IPCfgJson
			c.BindJSON(&ipC)
			result, err := SetAddr(ipC)
			webapi.SendResult(result, err, c)

		})
	}
}
